class NFCServices {

	readyWriteData = false; //开启写
	readyRead = false; //开启读
	noNFC = false;
	callBack = null;
	readyData = ''; //准备写入的数据
	static techListsArray = [
		['android.nfc.tech.IsoDep'],
		['android.nfc.tech.NfcA'],
		['android.nfc.tech.NfcB'],
		['android.nfc.tech.NfcF'],
		['android.nfc.tech.Nfcf'],
		['android.nfc.tech.NfcV'],
		['android.nfc.tech.NdefFormatable'],
		['android.nfc.tech.MifareClassi'],
		['android.nfc.tech.MifareUltralight']
	];
	// 要写入的数据

	static package_TECH_DISCOVERED = 'android.nfc.action.TECH_DISCOVERED';
	static READ_SUCCESS = '1' //读取成功
	static READ_FAIL = '2' //读取失败
	static READING = '3' //正在读取
	static WRITING = '4' //正在写入
	static WRITE_SUCCESS = '5' //写入成功
	static WRITE_FAIL = '6' //写入失败
	static DEVICE_NO_NFC = '7' //设备不支持NFC
	static DEVICE_NFC_NOT_ENABLE = '8' //设备未开启NFC
	static DEVICE_NFC_NOT_ENABLE = '9' //设备未开启NFC
	static INIT = '10' //初始化NFC
	static INIT_ERROR = '11' //初始化NFC失败

	constructor(callBack, continuousRead) {
		//是否连续读取NFC数据
		this.isContinuousRead = continuousRead !== undefined ? continuousRead : true

		this.callBack = callBack
		this.RuntimeMainActivity = plus.android.runtimeMainActivity();
		this.Intent = plus.android.importClass('android.content.Intent');
		this.PendingIntent = plus.android.importClass('android.app.PendingIntent');
		this.IntentFilter = plus.android.importClass('android.content.IntentFilter');
		this.NfcAdapter = plus.android.importClass('android.nfc.NfcAdapter');
		this.NdefRecord = plus.android.importClass("android.nfc.NdefRecord");
		this.NdefMessage = plus.android.importClass("android.nfc.NdefMessage");
		this.Ndef = plus.android.importClass('android.nfc.tech.Ndef');
		this.NdefFormatable = plus.android.importClass('android.nfc.tech.NdefFormatable');
		// this.Parcelable = plus.android.importClass("android.os.Parcelable");
	}
	listenNFCStatus() {
		if (uni.getSystemInfoSync().platform !== "android") {
			return
		}
		this.callBack(NFCServices.INIT, '监听NFC状态！')
		try {

			let nfcAdapter = this.NfcAdapter.getDefaultAdapter(this.RuntimeMainActivity);

			if (nfcAdapter == null) {
				this.callBack(NFCServices.DEVICE_NO_NFC, '设备不支持NFC！')
				this.noNFC = true;
				return;
			}

			if (!nfcAdapter.isEnabled()) {
				this.callBack(NFCServices.DEVICE_NFC_NOT_ENABLE, '请在系统设置中先启用NFC功能！')
				this.noNFC = true;
				return;
			} else {
				this.noNFC = false;
			}

			let intent = new this.Intent(this.RuntimeMainActivity, this.RuntimeMainActivity.getClass());
			intent.addFlags(this.Intent.FLAG_ACTIVITY_SINGLE_TOP);
			let pendingIntent = this.PendingIntent.getActivity(this.RuntimeMainActivity, 0, intent, 0);
			let ndef = new this.IntentFilter("android.nfc.action.TECH_DISCOVERED");
			ndef.addDataType("*/*");
			let intentFiltersArray = [ndef];
			const that = this
			plus.globalEvent.addEventListener('newintent', () => {
				console.log('newintent running');
				// 轮询调用 NFC
				that.nfcRuning()
				// setTimeout(, 1000);
			});

			plus.globalEvent.addEventListener('pause', (e) => {
				console.log('pause running');
				if (nfcAdapter) {
					//关闭前台调度系统 恢复默认状态
					nfcAdapter.disableForegroundDispatch(this.RuntimeMainActivity);
				}
			});
			plus.globalEvent.addEventListener('resume', (e) => {
				if (nfcAdapter) {
					//开启前台调度系统 优于所有其他NFC
					nfcAdapter.enableForegroundDispatch(this.RuntimeMainActivity, pendingIntent,
						intentFiltersArray,
						NFCServices.techListsArray);
				}
			});

			nfcAdapter.enableForegroundDispatch(this.RuntimeMainActivity, pendingIntent, intentFiltersArray,
				NFCServices.techListsArray);
		} catch (e) {
			this.callBack(NFCServices.INIT_ERROR, '初始化NFC失败！', e)

		}

	}
	nfcRuning() { //

		let intent = this.RuntimeMainActivity.getIntent();
		if (NFCServices.package_TECH_DISCOVERED == intent.getAction()) {
			if (this.readyWriteData) {
				this.write(intent);
				this.readyWriteData = false;
			} else if (this.isContinuousRead || this.readyRead) {
				this.read(intent);
				this.readyRead = false;
			}

		}
	}
	write(intent) { //写代码
		try {
			this.callBack(NFCServices.WRITING, '请勿移开标签 正在写入...')
			let textBytes = plus.android.invoke(this.readyData, "getBytes");
			// image/jpeg text/plain  
			let textRecord = new this.NdefRecord(this.NdefRecord.TNF_MIME_MEDIA,
				plus.android.invoke("text/plain", "getBytes"),
				plus.android.invoke("", "getBytes"), textBytes);
			let message = new this.NdefMessage([textRecord]);

			let tag = intent.getParcelableExtra(this.NfcAdapter.EXTRA_TAG);
			let ndef = this.Ndef.get(tag);
			if (ndef != null) {
				// 待写入的数据长度
				let size = message.toByteArray().length;
				ndef.connect();
				if (!ndef.isWritable()) {
					this.callBack(NFCServices.WRITE_FAIL, 'tag不允许写入！')

					return;
				}
				if (ndef.getMaxSize() < size) {
					this.callBack(NFCServices.WRITE_FAIL, '文件大小超出容量！')
					return;
				}
				ndef.writeNdefMessage(message); //写入数据
				this.callBack(NFCServices.WRITE_SUCCESS, '写入数据成功！', this.readyData)
				return;
			} else {
				let format = this.NdefFormatable.get(tag);
				if (format != null) {
					try {
						format.connect();
						format.format(message);
						this.callBack(NFCServices.WRITE_SUCCESS, '格式化tag并且写入数据成功！', this.readyData)

						return;
					} catch (e) {
						this.callBack(NFCServices.WRITE_FAIL, '格式化tag失败！')
						return;
					}
				} else {
					this.callBack(NFCServices.WRITE_FAIL, 'Tag不支持NDEF！')
					return;
				}
			}
		} catch (e) {
			this.callBack(NFCServices.WRITE_FAIL, '写入失败！', e)
		}

	}
	read(intent) { // 读代码
		this.callBack(NFCServices.READING, '请勿移开标签正在读取数据！')
		// NFC id
		let bytesId = intent.getByteArrayExtra(this.NfcAdapter.EXTRA_ID);
		let nfc_id = this.byteArrayToHexString(bytesId);
		console.log('nfc_id:', nfc_id);

		// 卡内信息
		let rawmsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
		//let rawmsgs = intent.getParcelableArrayExtra();

		console.log("数据" + rawmsgs)
		if (rawmsgs != null && rawmsgs.length > 0) {
			let records = rawmsgs[0].getRecords();
			let result = records[0].getPayload();
			let data = plus.android.newObject("java.lang.String", result);

			this.callBack(NFCServices.READ_SUCCESS, '读取数据成功！', data)
		} else {
			this.callBack(NFCServices.READ_FAIL, '没有读取到数据！')
		}
	}
	// 将字节数组转换为字符串  
	byteArrayToHexString(inarray) {
		let i, j, inn;
		let hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
		let out = "";

		for (j = 0; j < inarray.length; ++j) {
			inn = inarray[j] & 0xff;
			i = (inn >>> 4) & 0x0f;
			out += hex[i];
			i = inn & 0x0f;
			out += hex[i];
		}
		return out;
	}
	// 更改写状态
	writeData(data) {
		if (this.noNFC) {
			this.callBack(NFCServices.WRITE_FAIL, '请检查设备是否支持并开启 NFC 功能！')

			return;
		}
		this.readyData = data
		// 轮询条件
		this.readyWriteData = true;
		this.callBack(NFCServices.WRITING, '请将NFC标签靠近！')
	}

	readData() { // 更改读状态
		if (this.noNFC) {
			this.callBack(NFCServices.READ_FAIL, '请检查设备是否支持并开启 NFC 功能！')

			return;
		}
		// 轮询条件
		this.readyRead = true;
		this.callBack(NFCServices.READING, '请将NFC标签靠近！')

	}
	// 设置数据
	destroy() {
		plus.globalEvent.removeEventListener('newintent', false);
		plus.globalEvent.removeEventListener('pause', false);
		plus.globalEvent.removeEventListener('resume', false);
	}
}
export default NFCServices

